package de.preisrobot.persistence.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import de.preisrobot.entity.CrawlerLinkUrl;

@Repository(value="linkDao")
public class LinkDaoImpl implements LinkDao {

	@PersistenceContext
	EntityManager em;

	@Override
	public List<CrawlerLinkUrl> findLinksForAnbieter(int anbieterid) {
		Query query = em
				.createQuery("select c from CrawlerLinkUrl c where c.anbieterId= ?1");
		query.setParameter(1, anbieterid);
		return query.getResultList();
	}

	@Override
	public CrawlerLinkUrl findLinlByUrl(String sourceUrlString) {
		Query query = em.createNativeQuery(
				"select * from anbieterlinks c where c.link = '"
						+ sourceUrlString + "' ", CrawlerLinkUrl.class);

		List<CrawlerLinkUrl> object = query.getResultList();
		if (object.isEmpty())
			return null;

		return object.get(0);
	}
	
	
	
	@Override
   public long save(CrawlerLinkUrl oobj) {
      em.persist(oobj);
      return oobj.getId();
         
   }
	
	  @Override
	   @Transactional(propagation=Propagation.REQUIRED)
	   public void updateLink(CrawlerLinkUrl link) {
	      CrawlerLinkUrl find = em.find(CrawlerLinkUrl.class, link.getId());
	      find.setLastvisited(link.getLastvisited());
	      find.setBrokenLink(link.getBrokenLink());
	      find.setLink(link.getLink());
	      find.setAnbieterId(link.getAnbieterId());
	   
	      em.persist(find);
	      
	   }

   @Override
   public List<CrawlerLinkUrl> findLinksByContent(String sourceUrlString)
   {  
   
      Query query = em.createNativeQuery(
            "select * from anbieterlinks c where c.link like '%"
                  + sourceUrlString + "%' ", CrawlerLinkUrl.class);

      List<CrawlerLinkUrl> object = query.getResultList();
    
      return object;
   }
}
